package org.bing.engine.common.message.handler;

import java.util.Map;

import org.bing.engine.common.message.Handler;
import org.bing.engine.common.message.HandlerAdapter;
import org.bing.engine.common.message.Message;

public class TypeBaseHandler extends HandlerAdapter {
    private Map<String, Handler> handlers;

    public void setHandlers(Map<String, Handler> handlers) {
        this.handlers = handlers;
    }

    @Override
    public Message handle(Message msg) {
        Handler handler = getHandler(msg);
        if (handler != null) {
            return handler.handle(msg);
        } else {
            logger.warn("Can't find handler for " + msg);
            return super.handle(msg);
        }
    }

    private Handler getHandler(Message msg) {
        if (msg.getBody() == null) {
            return null;
        } else {
            String clazz = msg.getBody().getClass().getName();
            return handlers.get(clazz);
        }
    }
}
